package net.wangds.redis.comp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2020/5/19 22:33.
 */
@Component
public class RedisComp {

    @Autowired
    RedisTemplate redisTemplate;

    public long incr() {
        String key = "LOCK-KEY-"+System.currentTimeMillis();
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("LOCK-KEY-"+key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if (null == increment || increment.longValue() == 0) {//初始设置过期时间
            entityIdCounter.expire(2, TimeUnit.MILLISECONDS);
        }

        return increment;
    }


    public long incrSecond() {
        String key = "LOCK-KEY-"+(System.currentTimeMillis()/1000);
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("LOCK-KEY-"+key, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        Long increment = entityIdCounter.getAndIncrement();

        if (null == increment || increment == 0) {//初始设置过期时间
            entityIdCounter.expire(2, TimeUnit.SECONDS);
        }

        return increment;
    }


    public long incrMinute() {
        String key = "LOCK-KEY-"+(System.currentTimeMillis()/60000);
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("LOCK-KEY-"+key, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        Long increment = entityIdCounter.getAndIncrement();

        if (null == increment || increment == 0) {//初始设置过期时间
            entityIdCounter.expire(2, TimeUnit.MINUTES);
        }

        return increment;
    }


    public long incrHour() {
        String key = "LOCK-KEY-"+(System.currentTimeMillis()/3600000);
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("LOCK-KEY-"+key, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        Long increment = entityIdCounter.getAndIncrement();

        if (null == increment || increment == 0) {//初始设置过期时间
            entityIdCounter.expire(2, TimeUnit.HOURS);
        }

        return increment;
    }


}
